#include "StdAfx.h"
#include "MapImport.h"
#include "EntityFactory.h"
#include "BaseEntity.h"

#include "../shared/geom.h"
#include "../shared/StringUtil.h"
#include "../Kernel.h"

extern Kernel* g_kernel;

const std::string MapImport::VERSION = "v1.0";

MapImport::MapImport(void)
{
}

MapImport::~MapImport(void)
{
}

/** Check the version */
bool MapImport::CheckFileVersion( const std::string &v )
{
    bool isRightV = VERSION == v;
    if ( !isRightV ) g_kernel->LPrintf( ("ERROR:: Conflict of version types, the current version is: " + VERSION + " this version is: " + v).c_str() );

    return isRightV;
}

/** Load a new map */
bool MapImport::OpenStream( const std::string &mapFile )
{
    StringUtil util(mapFile, '.');
    // get the name of the map
    if ( util.HasNext() )
        m_fileName = util.GetNext();

    // TODO:: Check if the .pak is loaded and if the file exists?
    return true;
}


/** Load the Entities */
type_EntList    MapImport::LoadEntities()
{
    type_EntList    entList;
    std::string nameOfFile = m_fileName + ".ent";

    // load the file
    MFile* file = g_kernel->GetVFileSystem()->OpenFile( nameOfFile );
    if ( !file )
    {
        g_kernel->LPrintf( ("ERROR:: Could not load: " + nameOfFile).c_str() );
        return entList;
    }

    /**
        Make sure this file is the right version
    */
    if ( ! CheckFileVersion( file->ReadNext(":") ) )
    {
        return entList;
    }

    /**
        Read in all the ents
    */
    while( !file->IsEnd() )
    {
        entList.push_back( ReadNext( file ) );
    }


    return entList;
}

/** Read the next entity */
BaseEntity* MapImport::ReadNext( MFile* file )
{
    /**
        Create the entity
    */
    BaseEntity* ent = EntityFactory::GetInstance()->CreateEntity( file->ReadNext(":") );
    if ( ent )
    {
        ent->SetName( file->ReadNext(":") );        // read the name of this entity
        file->ReadNext("{");
        file->ReadLine();

        /**
            Read the starting pos
        */
        MVector3f   position(   file->ReadDouble(),
                                file->ReadDouble(),
                                file->ReadDouble()
                            );
        ent->SetPosition( position );

        //==========================================
        // TODO:: Read other properties
        //==========================================

        file->ReadNext("}");
        file->ReadLine();
    }

    return ent;
}